package com.self.member.vo;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.self.common.exception.BusinessException;
import com.self.common.util.IpUtil;
import com.self.member.geetest.GeetestLib;
import com.self.member.geetest.GeetestLibResult;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;

/**
 * @version v1.0
 * @ClassName: GeetestBaseVo
 * @Description:
 * @Author: Mac
 * @Date: 2022/6/18 10:12
 */
@Data
public class GeetestBase {

    @ApiModelProperty(value = "用户的uuid")
    @NotBlank
    private String uuid;

    @ApiModelProperty(value = "极验的challenge")
    @JsonProperty(value = "geetest_challenge")
    private String geetestChallenge;

    @ApiModelProperty(value = "极验的validate")
    @JsonProperty(value = "geetest_validate")
    private String geetestValidate;

    @ApiModelProperty(value = "极验的seccode")
    @JsonProperty(value = "geetest_seccode")
    private String geetestSeccode;

    public void check(RedisTemplate<String,Object> redisTemplate, GeetestLib geetestLib) {
        String challenge = this.geetestChallenge;
        String validate = this.geetestValidate;
        String seccode = this.geetestSeccode;
        int status = 0;
        String userId = "";
        // session必须取出值，若取不出值，直接当做异常退出
        String statusStr = redisTemplate.opsForValue().get(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY+ ":" + this.getUuid()).toString();
        status = Integer.valueOf(statusStr).intValue();
        userId = redisTemplate.opsForValue().get(GeetestLib.GEETEST_SERVER_USER_KEY + ":" + this.getUuid()).toString();
        GeetestLibResult result = null;
        if (status == 1){
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("user_id", userId);
            paramMap.put("client_type", "web");
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            paramMap.put("ip_address", IpUtil.getIpAddr(servletRequestAttributes.getRequest()));
            result = geetestLib.successValidate(challenge, validate, seccode, paramMap);
        }else{
            result = geetestLib.failValidate(challenge, validate, seccode);
        }
        if (result.getStatus() != 1){
            throw new BusinessException("验证码验证异常") ;
        }

    }


}
